﻿using Common;
using Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Filters;

namespace WebApi
{
    public class UsersAuthorizeAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(HttpActionContext actionContext)
        {
            var notAuthorize = actionContext.ActionDescriptor.GetCustomAttributes<NotAuthorizeAttribute>();
            if (notAuthorize.Any())
            {
                base.OnActionExecuting(actionContext);
                return;
            }
            (string, JWTModel) checkResult;//（token错误信息，JWT模型）
            IEnumerable<string> userToken;
            bool getToken = actionContext.Request.Headers.TryGetValues("User-Token", out userToken);
            if (getToken)
            {
                string token = userToken?.First();
                if (string.IsNullOrWhiteSpace(token)
                || token == "null"
                || token == "undefined")
                {
                    actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized, new Result { Code = CustomCodeEnum.Expired, Message = "没有token" });
                    return;
                }

                checkResult = JWTHelper.CheckToken(token);
                if (!string.IsNullOrWhiteSpace(checkResult.Item1))
                {
                    actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized, new Result { Code = CustomCodeEnum.Expired, Message = checkResult.Item1 });
                    return;
                }
            }
            else
            {
                actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized, new Result { Code = CustomCodeEnum.Expired, Message = "没有token" });
                return;
            }

            //tonken通过。
            base.OnActionExecuting(actionContext);
            return;
        }
    }

    //匿名访问特性
    public class NotAuthorizeAttribute : Attribute
    {
    }
}